package net.arogarth.aws.android.manager.views;

import java.util.ArrayList;
import java.util.List;

import net.arogarth.aws.android.lib.AmazonEc2;
import net.arogarth.aws.android.lib.AwsRequestException;
import net.arogarth.aws.android.lib.def.Ec2InstanceState;
import net.arogarth.aws.android.lib.models.Ec2Instance;
import net.arogarth.aws.android.manager.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Ec2InstanceList extends Activity {
	public class Ec2ListAdapter extends BaseAdapter implements OnItemLongClickListener {

		private final List<Ec2Instance> instances = new ArrayList<Ec2Instance>();

		public boolean showDetails = false;
		
		final ProgressDialog pd;
		
		private Context context;

		public String[] filterInstances = { };
		
		public Ec2ListAdapter(Context view, ListView list) {
			this.context = view;

			list.setAdapter(this);
			list.setOnItemLongClickListener(this);

			pd = ProgressDialog.show(this.context,
					"Please wait...", "Loading Data...", true, false);
			
			this.loadData();
		}

		private void loadData() {
			
			final Thread t = new Thread() {
				public void run() {
					AmazonEc2 aec2 = new AmazonEc2();

					boolean allFinished = false;
					
					while(!allFinished) {
						try {
							allFinished = true;
							Log.d("LOOP", "aktualisiere...");
							
							for(int i=0; i < filterInstances.length; i++) {
								aec2.params.put(
										String.format("InstanceId.%s", i), filterInstances[i]);
							}
							
							List<Ec2Instance> _instances = aec2.descriptInstances();
	
							instances.clear();
							for (Ec2Instance instance : _instances) {
								instances.add(instance);
								
								if( instance.getInstanceState().equals(Ec2InstanceState.PENDING)
								 || instance.getInstanceState().equals(Ec2InstanceState.SHUTTING_DOWN)
								 || instance.getInstanceState().equals(Ec2InstanceState.STOPPING) ) {
									allFinished = false;
								}
							}
	
//							tags.clear();
//							List<Ec2Tag> _tags = aec2.descriptTags();
//							for (Ec2Tag tag : _tags) {
//								tags.add(tag);
//							}
	
							runOnUiThread(new Runnable() {
								public void run() {
									notifyDataSetChanged();
									pd.dismiss();
								}
							});
						} catch (final AwsRequestException e) {
							runOnUiThread(new Runnable() {
								public void run() {
									Toast.makeText(context, e.getMessage(),
											Toast.LENGTH_SHORT).show();
									finish();
								}
							});
						}
					}
				}
			};
			t.start();
		}

		public int getCount() {
			return this.instances.size();
		}

		public Ec2Instance getItem(int arg0) {
			return (Ec2Instance) this.instances.get(arg0);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final Ec2Instance instance = (Ec2Instance) getItem(position);

			final LinearLayout _ll = (LinearLayout) LayoutInflater.from(
					this.context).inflate(R.layout.ec2_instance_list_item, parent,
					false);

			String name = instance.getInstanceId();

			
			if(instance.getTagSet().containsKey("Name")) {
				name +=  " (" + instance.getTagSet().get("Name") + ")";
			}

			final String title = name;

			((TextView) _ll.findViewById(R.id.instanceId)).setText(title);
			((TextView) _ll.findViewById(R.id.tvState)).setText(instance
					.getInstanceState().name().toLowerCase());
			
			if(!this.showDetails) {
				_ll.removeView( _ll.findViewById(R.id.instanceDetails) );
			} else {
				// PropertyList
				((TextView) _ll.findViewById(R.id.tvInstanceType)).setText(instance.getInstanceType().toLowerCase());
				((TextView) _ll.findViewById(R.id.tvLaunchTime)).setText(instance.getInstanceLaunchTime().toLowerCase());
				((TextView) _ll.findViewById(R.id.tvKeyName)).setText(instance.getKeyName().toLowerCase());
				
				((TextView) _ll.findViewById(R.id.tvArchitecture)).setText(instance.getArchitecture().name());
				
				((TextView) _ll.findViewById(R.id.tvPrivateIp)).setText(instance.getPrivateIpAddress().toLowerCase());
				((TextView) _ll.findViewById(R.id.tvPrivateDns)).setText(instance.getPrivateDnsName().toLowerCase());
				
				((TextView) _ll.findViewById(R.id.tvPublicIp)).setText(instance.getPublicIpAddress().toLowerCase());
				((TextView) _ll.findViewById(R.id.tvPublicDns)).setText(instance.getPublicDnsName().toLowerCase());
			}
			ImageView iv = ((ImageView) _ll.findViewById(R.id.instanceStatus));

			if (instance.getInstanceState() != null) {
				switch (instance.getInstanceState()) {
				case RUNNING:
					iv.setImageResource(R.drawable.greenled);
					break;
				case STOPPED:
					iv.setImageResource(R.drawable.redled);
					break;
				default:
					iv.setImageResource(R.drawable.yellowled);
					break;
				}
			}

			return _ll;
		}

		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int position, long arg3) {
			final Ec2Instance instance = this.getItem(position);

			AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
			builder.setTitle(instance.getInstanceId());

			final ArrayAdapter<CharSequence> adapter = ArrayAdapter
					.createFromResource(this.context, R.array.ec2Options,
							android.R.layout.select_dialog_item);

			builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					try {
						switch (which) {
						
						// case 0: // Connect
						// // new
						// // AmazonEc2().startInstance(instance.getInstanceId());
						// break;
						// case 1: // Create Snapshot
						// // new
						// // AmazonEc2().startInstance(instance.getInstanceId());
						// break;
						// case 2: // Launch More Like This
						// // new
						// // AmazonEc2().startInstance(instance.getInstanceId());
						// break;
						case 0: // Start
							new AmazonEc2()
									.startInstance(instance);
							break;
						case 1: // Stop
							new AmazonEc2()
									.stopInstance(instance);
							break;
						case 2: // Terminate
							new AmazonEc2()
									.terminateInstance(instance);
							break;
						}
						
						loadData();
					} catch (Exception e) {
					}
					adapter.notifyDataSetChanged();
				}
			});

			builder.create().show();

			return true;
		}
	}
	Ec2ListAdapter adapter;
			
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.basic_list);
		final ListView lv = (ListView) findViewById(R.id.contentlist);
		adapter = new Ec2ListAdapter(Ec2InstanceList.this, lv);
		
		if(getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().containsKey("instances")) 
			adapter.filterInstances = getIntent().getExtras().getStringArray("instances");
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.ec2_instances, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.miMore:
			adapter.showDetails = !adapter.showDetails;
			adapter.notifyDataSetChanged();
			
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
